import React, { useEffect, useRef, useState } from 'react'
import { createStyles } from 'antd-style'
import FileOption from './FileOption'
import { deleteFile, getFile, getFolders, updateFolderId } from '~/api/file'
import { FileInfo, Folder, UpdateFolderId, fileInfo } from '~/types'
import { useStoreDispatch, useStoreSelector } from '~/store'
import FileRenderer from './FileRenderer'
import Breadcrumb from '../Breadcrumb'
import { Input, message } from 'antd'
import {
  Breadcrumbs,
  setBreadcrumbs,
  setTotalSize
} from '~/store/features/fileSlice'
import Modal, { CustomModalHandles } from '../Modal'
import FolderIcon from '~/assets/folder.png'
import JSZip from 'jszip'
import { createShare } from '~/api/share'
import QRCode from 'qrcode.react'

const downloadFile = async (url: string | URL | Request) => {
  const response = await fetch(url)
  if (!response.ok) {
    throw new Error(`Failed to download file: ${response.statusText}`)
  }
  return await response.arrayBuffer()
}

const FileList: React.FC = () => {
  const [files, setFiles] = useState<fileInfo[]>([])
  const [folders, setFolders] = useState<fileInfo[]>([])
  const [shareName, setShareName] = useState<string>('')
  const [shareLink, setShareLink] = useState<string>('')
  const [folderBreadcrumbs, setFolderBreadcrumbs] = useState<Breadcrumbs[]>([])
  const { styles } = useStyles()
  const {
    file: { folder, breadcrumbs },
    user
  } = useStoreSelector((state) => state)
  const modalRef = useRef<CustomModalHandles>(null)
  const shareModalRef = useRef<CustomModalHandles>(null)

  const dispatch = useStoreDispatch()
  useEffect(() => {
    getFileList(folder)
  }, [folder])
  useEffect(() => {
    const getFolder = async () => {
      const res = {
        userId: folder.userId,
        folderId: folderBreadcrumbs[folderBreadcrumbs.length - 1].id
      }
      console.log('🚀 ~ getFolder ~ res.folderBreadcrumbs:', folderBreadcrumbs)
      const { data } = await getFolders(res)
      if (!data) return
      setFolders(data)
    }
    folderBreadcrumbs.length > 0 && getFolder()
  }, [folderBreadcrumbs])
  const getFileList = async (userInfo: FileInfo) => {
    console.log('🚀 ~ getFileList ~ userInfo触发了:', userInfo)
    const { data } = await getFile(userInfo)
    if (!data) return
    // 对其进行排序
    const res = data!.list!.sort((a, b) => a.typeId - b.typeId)
    res.forEach((item, index) => {
      if (item.isCheck === undefined) {
        item.isCheck = false // 或者根据你的逻辑设置默认值
      }
      item.url =
        import.meta.env.VITE_APP_IMG_URL +
        (item.url ? item.url : '/' + item.name)
    })
    setFiles(res)
    dispatch(setTotalSize(data.totalSize))
  }
  const showModal = async (type: string) => {
    if (type === 'move') {
      setFolderBreadcrumbs([{ id: user!.userInfo!.folderId, name: '首页' }])
      modalRef.current?.openModal()
    } else {
      shareModalRef.current?.openModal()
    }
  }
  // 确定移动按钮
  const handleFileNew = async () => {
    const breadcrumbs = folderBreadcrumbs.map((item) => item.id)
    console.log('🚀 ~ handleFileNew ~ breadcrumbs:', breadcrumbs)
    const res = files.reduce<UpdateFolderId>(
      (acc, item) => {
        if (item.isCheck) {
          if (!breadcrumbs.includes(item.id) && item.fileType === 'folder') {
            acc.folderList.push(item.id)
          } else {
            acc.fileList.push(item.id)
          }
        }
        return acc
      },
      {
        folderList: [],
        fileList: [],
        folderId: breadcrumbs[breadcrumbs.length - 1]
      }
    )
    await updateFolderId(res)
    getFileList(folder)
  }
  // 确定分享按钮
  const handleShare = async () => {
    const res = files.reduce<UpdateFolderId>(
      (acc, item) => {
        if (item.isCheck) {
          if (item.fileType === 'folder') {
            acc.folderList.push(item.id)
          } else {
            acc.fileList.push(item.id)
          }
        }
        return acc
      },
      {
        folderList: [],
        fileList: []
      }
    )
    const { data } = await createShare({
      ...res,
      shareName,
      userId: folder.userId
    })
    setShareLink(window.location.origin + '/share?code=' + data)
  }
  const handleFolder = async (item: Breadcrumbs) => {
    setFolderBreadcrumbs([
      ...folderBreadcrumbs,
      {
        name: item.name,
        id: item.id
      }
    ])
  }
  // 分享、下载、移动、删除操作
  const changeFile = async (btnId: number) => {
    const fileList = files.filter((item) => item.isCheck)
    if (fileList.length === 0) return message.warning('请先选择文件！！！！')
    console.log('🚀 ~ changeFile ~ fileList:', fileList)
    if (btnId === 1) {
      //分享
      showModal('share')
    } else if (btnId === 2) {
      //下载
      downloadFilesAndFolders(fileList, 'MyFolder')
    } else if (btnId === 3) {
      //移动
      showModal('move')
    } else if (btnId === 4) {
      // 将所有删除操作的 promise 放入一个数组中
      const deletePromises = fileList.map((item) => {
        console.log('item', item)
        return deleteFile(item) // 假设 deleteFile 返回一个 promise
      })
      // 等待所有删除操作完成
      await Promise.all(deletePromises)
      getFileList(folder)
      //删除
      console.log('删除')
    }
    console.log('files', files)
  }
  const downloadFilesAndFolders = async (
    fileList: fileInfo[],
    folderName: string
  ) => {
    const zip = new JSZip()

    const addFilesToZip = async (zipFolder: JSZip, files: fileInfo[]) => {
      for (const file of files) {
        if (file.fileType === 'folder') {
          // 创建一个新的文件夹
          const newZipFolder: JSZip = zipFolder.folder(file.name)!
          // 假设 getFileList 是一个 API，用于获取文件夹中的文件列表
          const { data } = await getFile({ ...folder, folderId: file.id })
          data?.list.forEach((item) => {
            if (item.fileType !== 'folder') {
              item.url = import.meta.env.VITE_APP_IMG_URL + item.url
            }
          })
          // 递归添加文件和子文件夹
          await addFilesToZip(newZipFolder, data!.list)
        } else {
          // 下载文件并添加到 ZIP 包中
          const fileData = await downloadFile(file.url) // 假设 downloadFile 是一个函数，用于下载文件并返回 ArrayBuffer
          zipFolder.file(file.name + '.' + file.type, fileData, {
            binary: true
          })
        }
      }
    }
    // 在生成 ZIP 包之前输出 fileList 的 JSON 数据
    console.log('File list JSON:', JSON.stringify(fileList, null, 2))
    await addFilesToZip(zip, fileList)

    // 生成 ZIP 包并触发下载
    zip.generateAsync({ type: 'blob' }).then((content) => {
      const url = window.URL.createObjectURL(content)
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', `${folderName}.zip`)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    })
  }
  return (
    <div className={`${styles.container} mx-2 bg-white`}>
      <FileOption getFileList={getFileList} changeFile={changeFile} />
      <Breadcrumb
        breadcrumbs={breadcrumbs}
        cb={(index) => dispatch(setBreadcrumbs(breadcrumbs.slice(0, index)))}
      />
      <FileRenderer files={files} />
      <Modal ref={modalRef} title='文件移动' onConfirm={handleFileNew}>
        <Breadcrumb
          breadcrumbs={folderBreadcrumbs}
          cb={(index) =>
            setFolderBreadcrumbs(folderBreadcrumbs.slice(0, index))
          }
        />
        <div className='flex flex-wrap'>
          {folders.length > 0 ? (
            folders.map((item) => (
              <div
                className={`${styles.folders} flex flex-col mb-4`}
                key={item.id}
                onClick={() => handleFolder(item)}
              >
                <img
                  className='mb-2'
                  style={{ width: '30px' }}
                  src={FolderIcon}
                  alt=''
                />
                {item.name}
              </div>
            ))
          ) : (
            <div className={`${styles.folders} flex flex-col ml-5`}>
              暂无文件夹
            </div>
          )}
        </div>
      </Modal>
      <Modal ref={shareModalRef} title='分享名称' onConfirm={handleShare}>
        <Input
          placeholder='分享名称'
          value={shareName}
          onChange={(e) => setShareName(e.target.value)}
        />
        {shareLink && (
          <div>
            <a href={shareLink}>{shareLink}</a>
            <QRCode value={shareLink} />
          </div>
        )}
      </Modal>
    </div>
  )
}

export default FileList

const useStyles = createStyles(({ token, css }) => {
  return {
    container: css`
      flex: 1;
      max-width: 100%;
      overflow: hidden;
      @media (min-width: 768px) {
        height: calc(100% - 5px);
      }
    `,
    img: css`
      width: 50px;
    `,
    folders: css`
      width: 70px;
      min-width: 70px;
      justify-content: center;
      align-items: center;
    `
  }
})
